<template>
  <div class="statistics-container">
    <div class="page-header">
      <!-- 两个下拉框 -->
      <span>指标编码：</span>
      <el-select v-model="indicatorCode" placeholder="请选择指标编码" clearable style="width: 200px; margin-right: 20px;">
        <el-option v-for="item in indicatorList" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>

<!--      <span>告警级别：</span>
      <el-select
        v-model="alarmLevel"
        placeholder="请选择告警级别"
        clearable
        style="width: 200px; margin-right: 20px;">
        <el-option
          v-for="item in alarmLevelList"
          :key="item.value"
          :label="item.label"
          :value="item.value">
          <span class="alarm-level-option">
            <span class="alarm-level-dot" :style="{ backgroundColor: item.color }"></span>
            <span>{{ item.label }}</span>
          </span>
        </el-option>
      </el-select>-->

      <!-- 新增按钮 -->
      <el-button type="primary" icon="el-icon-plus" @click="handleAdd" style="margin-left: auto;">新增</el-button>
    </div>

    <div class="page-content">
      <div class="card">
<!--        <div class="card-header">
          <span class="card-title">
            <i class="el-icon-document"></i>
            阈值配置列表页面
          </span>
        </div>-->
        <div class="card-body">
          <el-table
            :data="tableData"
            style="width: 100%"
            size="small"
            stripe
            :header-cell-style="{ background: '#f5f7fa', color: '#333', fontWeight: '500', fontSize: '12px', textAlign: 'center' }"
            :cell-style="{ fontSize: '12px', padding: '8px 0', textAlign: 'center', color: '#333' }"
            :fit="true">
            <el-table-column prop="index" label="序号" align="center">
              <template slot-scope="scope">
                {{ scope.$index + 1 + (queryParams.pageNum - 1) * queryParams.pageSize }}
              </template>
            </el-table-column>
            <el-table-column prop="indicatorCode" label="指标编码" align="center" header-align="center">
              <template slot-scope="scope">
                <el-tooltip :content="scope.row.indicatorCode" placement="top">
                  <span>{{ scope.row.metricLabel || scope.row.indicatorCode }}</span>
                </el-tooltip>
              </template>
            </el-table-column>
<!--            <el-table-column prop="alarmLevel" label="告警级别" align="center" header-align="center">
              <template slot-scope="scope">
                <el-tag
                  :type="getAlarmLevelType(scope.row.alarmLevel)"
                  size="small"
                  :effect="'plain'">
                  {{ scope.row.alarmLevel }}
                </el-tag>
              </template>
            </el-table-column>-->
            <el-table-column prop="preWarningValue" label="预警值" align="center" header-align="center">
              <template slot-scope="scope">
                {{ scope.row.preWarningValue || '-' }}
              </template>
            </el-table-column>
            <el-table-column prop="alarmValue" label="告警值" align="center" header-align="center">
              <template slot-scope="scope">
                {{ scope.row.alarmValue || '-' }}
              </template>
            </el-table-column>
            <el-table-column prop="comparisonOperator" label="比较符" align="center" header-align="center">
              <template slot-scope="scope">
                {{ scope.row.comparisonOperator || '-' }}
              </template>
            </el-table-column>
            <el-table-column prop="weight" label="权重" align="center" header-align="center">
              <template slot-scope="scope">
                {{ scope.row.weight || '-' }}
              </template>
            </el-table-column>

            <el-table-column label="操作" align="center" header-align="center">
              <template slot-scope="scope">
                <el-button size="mini" type="text" @click="handleEdit(scope.row)">编辑</el-button>
                <el-button size="mini" type="text" style="color: #f56c6c;" @click="handleDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页器 -->
          <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="handlePagination"
          />
        </div>
      </div>
    </div>

    <!-- 编辑对话框组件 -->
    <AlarmConfigDialog
      :visible.sync="dialogVisible"
      :form-data="formData"
      :indicator-list="indicatorList"
      :alarm-level-list="alarmLevelList"
      :is-edit="isEdit"
      @submit="handleSubmit"
      @cancel="handleCancel"
    />
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import AlarmConfigDialog from '@/views/statistics/components/alarmConfigDialog.vue';
import { getThresholdList, getThresholdDict, addThresholdConfig, deleteThresholdConfig, updateThresholdConfig } from '@/views/statistics/api/thresholdApi';

export default {
  name: 'Demo',
  components: {
    Pagination,
    AlarmConfigDialog
  },
  data() {
    return {
      // 下拉框数据
      indicatorCode: null,
      alarmLevel: null,

      // 指标编码列表
      indicatorList: [

      ],

      // 告警级别列表
      alarmLevelList: [
        { label: '一级告警', value: '一级告警', color: '#f56c6c' }, // 红色
        { label: '二级告警', value: '二级告警', color: '#e6a23c' }, // 橙色
        { label: '三级告警', value: '三级告警', color: '#409eff' }  // 蓝色
      ],

      // 表格数据
      tableData: [],

      // 分页参数
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      total: 0,

      // 编辑对话框相关
      dialogVisible: false,
      isEdit: false, // false为新增，true为编辑
      editIndex: -1, // 编辑时的索引
      editId: null, // 编辑时的记录ID
      formData: {
        indicatorCode: '',
        alarmLevel: '',
        preWarningValue: '',
        alarmValue: '',
        comparisonOperator: '',
        weight: '',
        scoringFormula: '',
        baselineHigh: '',
        baselineLow: ''
      },

      // 模拟的完整数据
      allData: [
      ]
    }
  },
  watch: {
    indicatorCode() {
      this.queryParams.pageNum = 1 // 重置到第一页
      this.filterAndPaginate()
    },
    alarmLevel() {
      this.queryParams.pageNum = 1 // 重置到第一页
      this.filterAndPaginate()
    }
  },
  mounted() {
    this.getList()
  },
  methods: {
    // 获取列表数据
    getList() {
      getThresholdList().then(res => {
        console.log("&*&%%%%",res.code,res.rows)
        if(res.code === 200 && res.rows) {
          // 映射数据
          this.allData = res.rows.map(item => {
            // 转换告警级别格式
            let alarmLevelDisplay = ''
            if (item.alarm_level === 'level1' || item.alarm_level === 'Level1' || item.alarm_level === '一级告警') {
              alarmLevelDisplay = '一级告警'
            } else if (item.alarm_level === 'level2' || item.alarm_level === 'Level2' || item.alarm_level === '二级告警') {
              alarmLevelDisplay = '二级告警'
            } else if (item.alarm_level === 'level3' || item.alarm_level === 'Level3' || item.alarm_level === '三级告警') {
              alarmLevelDisplay = '三级告警'
            } else if (item.alarm_level === 'score') {
              alarmLevelDisplay = '其他' // score 在表格中显示为"其他"
            } else {
              alarmLevelDisplay = '其他' // 未匹配到的显示"其他"
            }

            // 格式化权重：如果是数字，转换为百分比
            let weightDisplay = '-'
            if (item.score_weight !== null && item.score_weight !== undefined) {
              if (typeof item.score_weight === 'number') {
                weightDisplay = (item.score_weight * 100).toFixed(0) + '%'
              } else {
                weightDisplay = item.score_weight
              }
            }

            // 格式化更新时间
            let updateTimeDisplay = '-'
            if (item.updated_at) {
              // 将 ISO 格式转换为 YYYY-MM-DD HH:mm:ss
              const date = new Date(item.updated_at)
              if (!isNaN(date.getTime())) {
                updateTimeDisplay = date.toLocaleString('zh-CN', {
                  year: 'numeric',
                  month: '2-digit',
                  day: '2-digit',
                  hour: '2-digit',
                  minute: '2-digit',
                  second: '2-digit',
                  hour12: false
                }).replace(/\//g, '-')
              }
            }

            return {
              id: item.id,
              indicatorCode: item.metric_code || '-',
              metricLabel: item.metricLabel || item.metric_label || item.metric_code || '-', // 显示标签
              alarmLevel: alarmLevelDisplay,
              alarmLevelRaw: item.alarm_level, // 保留原始值用于编辑
              preWarningValue: item.warn_value !== null && item.warn_value !== undefined ? String(item.warn_value) : '-',
              alarmValue: item.alarm_value !== null && item.alarm_value !== undefined ? String(item.alarm_value) : '-',
              comparisonOperator: item.comparator || item.comparison_operator || '-', // 优先使用 comparator，如果没有则使用 comparison_operator，都没有则显示 '-'
              weight: weightDisplay,
              weightRaw: item.score_weight, // 保留原始值用于编辑
              updateTime: updateTimeDisplay,
              scoringFormula: item.scoring_formula,
              baselineHigh: item.baseline_high,
              baselineLow: item.baseline_low
            }
          })

          // 数据映射完成后，执行过滤和分页
          this.filterAndPaginate()
        } else {
          this.allData = []
          this.filterAndPaginate()
        }
      }).catch(error => {
        console.error('获取阈值列表失败:', error)
        this.$message.error('获取数据失败')
        this.allData = []
        this.filterAndPaginate()
      });

      // 获取指标编码字典
      getThresholdDict('iot_metric_code').then(res => {
        if (res && Array.isArray(res)) {
          this.indicatorList = res.map(item => {
            const label = item.label || item.dictLabel || item.dict_label || item.value || item.dictValue || item.dict_value || ''
            const value = item.value || item.dictValue || item.dict_value || ''
            const type = item.type || item.dictType || item.dict_type || ''
            return {
              label,
              value,
              type
            }
          })
        } else {
          this.indicatorList = []
        }
      }).catch(error => {
        console.error('获取指标编码字典失败:', error)
      });
    },

    // 过滤和分页处理
    filterAndPaginate() {
      // 过滤数据
      let filteredData = this.allData.filter(item => {
        if (this.indicatorCode && item.indicatorCode !== this.indicatorCode) {
          return false
        }
        if (this.alarmLevel && item.alarmLevel !== this.alarmLevel) {
          return false
        }
        return true
      })

      // 更新总数
      this.total = filteredData.length

      // 分页处理
      const start = (this.queryParams.pageNum - 1) * this.queryParams.pageSize
      const end = start + this.queryParams.pageSize
      this.tableData = filteredData.slice(start, end)
    },

    // 处理分页事件
    handlePagination() {
      // .sync 修饰符已经自动更新了 queryParams.pageNum 和 queryParams.pageSize
      this.filterAndPaginate()
    },

    // 获取告警级别标签类型
    getAlarmLevelType(level) {
      if (level === '一级告警' || level === 'level1' || level === 'Level1') {
        return 'danger' // 红色
      } else if (level === '二级告警' || level === 'level2' || level === 'Level2') {
        return 'warning' // 橙色
      } else if (level === '三级告警' || level === 'level3' || level === 'Level3') {
        return 'info' // 蓝色
      }
      // 其他（未匹配到的）返回空字符串，显示灰色
      return ''
    },

    // 获取告警级别颜色
    getAlarmLevelColor(level) {
      const item = this.alarmLevelList.find(item => item.value === level)
      return item ? item.color : '#909399' // 默认灰色
    },

    // 获取告警级别标签文本
    getAlarmLevelLabel(level) {
      const item = this.alarmLevelList.find(item => item.value === level)
      return item ? item.label : level
    },

    // 新增
    handleAdd() {
      this.isEdit = false
      this.resetForm()
      this.dialogVisible = true
    },

    // 编辑
    handleEdit(row) {
      this.isEdit = true
      // 找到当前编辑的数据在 allData 中的索引（使用指标编码和告警级别作为唯一标识）
      this.editIndex = this.allData.findIndex(item =>
        item.indicatorCode === row.indicatorCode &&
        item.alarmLevel === row.alarmLevel
      )
      // 填充表单数据
      // 判断是否是指定的4个指标编码
      const specialCodes = ['temperature.max', 'alarm.total', 'fault.total', 'electrical.powerfactor']
      const isSpecialCode = specialCodes.includes(row.indicatorCode)

      this.formData = {
        indicatorCode: row.indicatorCode,
        // 如果是指定的指标编码，使用原始值（可能是 'score'），否则使用中文显示值
        alarmLevel: isSpecialCode ? (row.alarmLevelRaw || 'score') : row.alarmLevel,
        preWarningValue: row.preWarningValue === '-' ? '' : String(row.preWarningValue),
        alarmValue: row.alarmValue === '-' ? '' : String(row.alarmValue),
        comparisonOperator: row.comparisonOperator || '>',
        // 权重：如果是百分比格式，转换为小数；否则直接使用
        weight: row.weight === '-' ? '' : (row.weightRaw !== undefined && row.weightRaw !== null ? String(row.weightRaw) : ''),
        scoringFormula: row.scoringFormula || '',
        baselineHigh: row.baselineHigh !== null && row.baselineHigh !== undefined ? String(row.baselineHigh) : '',
        baselineLow: row.baselineLow !== null && row.baselineLow !== undefined ? String(row.baselineLow) : ''
      }
      // 保存当前编辑的 id，用于更新时传递
      this.editId = row.id
      this.dialogVisible = true
    },

    // 取消
    handleCancel() {
      this.dialogVisible = false
      this.resetForm()
    },

    // 提交表单
    handleSubmit(formDataCopy) {
      if (this.isEdit) {
        // 编辑模式：调用 API 更新数据，需要传递 id
        const updateData = {
          ...formDataCopy,
          id: this.editId
        }
        updateThresholdConfig(updateData).then(res => {
          if (res.code === 200) {
            this.$message.success('编辑成功')
            this.dialogVisible = false
            this.resetForm()
            this.getList()
          } else {
            this.$message.error(res.msg || '编辑失败')
          }
        }).catch(error => {
          console.error('编辑失败:', error)
          const errorMsg = error.response?.data?.msg || error.message || '编辑失败'
          this.$message.error('编辑失败：' + errorMsg)
        })
      } else {
        // 新增模式：调用 API 保存到数据库
        addThresholdConfig(formDataCopy).then(res => {
          if (res.code === 200) {
            this.$message.success('新增成功')
            this.dialogVisible = false
            this.resetForm()
            // 重置分页到第一页
            this.queryParams.pageNum = 1
            // 重新加载数据
            this.getList()
          } else {
            this.$message.error(res.msg || '新增失败')
          }
        }).catch(error => {
          console.error('新增失败:', error)
          const errorMsg = error.response?.data?.msg || error.message || '新增失败'
          this.$message.error('新增失败：' + errorMsg)
        })
      }
    },

    // 重置表单
    resetForm() {
      this.formData = {
        indicatorCode: '',
        alarmLevel: '',
        preWarningValue: '',
        alarmValue: '',
        comparisonOperator: '',
        weight: '',
        scoringFormula: '',
        baselineHigh: '',
        baselineLow: ''
      }
      this.editIndex = -1
      this.editId = null
    },

    // 删除
    handleDelete(row) {
      this.$confirm('确定要删除这条记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 调用删除接口
        deleteThresholdConfig(row.id).then(res => {
          if (res.code === 200) {
            this.$message.success('删除成功')
            this.getList() // 重新加载数据
          } else {
            this.$message.error(res.msg || '删除失败')
          }
        }).catch(error => {
          console.error('删除失败:', error)
          const errorMsg = error.response?.data?.msg || error.message || '删除失败'
          this.$message.error('删除失败：' + errorMsg)
        })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    }
  }
}
</script>

<style scoped lang="scss">
@import '@/views/statistics/style/screen.scss';

.page-header {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;

  span {
    font-size: 14px;
    color: #333;
    font-weight: 500;
  }
}

.page-content {
  .card {
    min-height: 500px;
  }

  .card-body {
    padding: 20px;
  }

  // 加深表格文字颜色
  ::v-deep .el-table {
    color: #333;

    .el-table__body {
      color: #333;
    }

    td {
      color: #333 !important;
    }

    th {
      color: #333 !important;
    }
  }
}
</style>

<style lang="scss">
// 告警级别下拉框选项样式（全局样式，因为下拉框渲染在 body 下）
.el-select-dropdown__item {
  .alarm-level-option {
    display: flex !important;
    align-items: center !important;
    gap: 8px;
  }

  .alarm-level-dot {
    display: inline-block !important;
    width: 10px !important;
    height: 10px !important;
    border-radius: 50% !important;
    flex-shrink: 0;
  }
}
</style>

